package com.kecheng.com.servlet;
  
  
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kecheng.dao.TeamDao;
import net.sf.json.JSONObject;
import com.kecheng.pojo.Keyword;
import com.kecheng.pojo.Team;
import com.kecheng.util.Delemoji;
import com.kecheng.util.SpringUtil;

import com.kecheng.com.utils.CommonUtil;
import com.kecheng.com.yx.message.resp.ImgMessage;
import com.kecheng.com.yx.message.resp.NewsMessage;
import com.kecheng.com.yx.message.resp.TextMessage;
import com.kecheng.com.yx.pojo.AccessToken;
import com.kecheng.com.yx.util.MessageUtil;
import com.kecheng.com.yx.util.WeixinUtil;

import com.kecheng.dao.IndexDao;

/**
 * 核心服务类 
 */ 
public class CoreService { 
	private static String respMessage = null;  
	// 第三方用户唯一凭证   
	private static TeamDao teamDao = (TeamDao) SpringUtil.getBean("teamDao");
	public static String processRequest(HttpServletRequest request,HttpServletResponse response,String appId,String appSecret) {  
        try {  
            // 默认返回的文本消息内容   
            String respContent = "";  
  
            // xml请求解析   
            Map<String, String> requestMap = MessageUtil.parseXml(request);  
            
            // 发送方帐号（open_id）   
            String fromUserName = requestMap.get("FromUserName");  
            // 公众帐号   
            String toUserName = requestMap.get("ToUserName");  
            // 消息类型   
            String msgType = requestMap.get("MsgType"); 
//        	//回复图片
            ImgMessage imgMessage = new ImgMessage();
            imgMessage.setToUserName(fromUserName);  
            imgMessage.setFromUserName(toUserName);  
            imgMessage.setCreateTime(new Date().getTime());
            imgMessage.setMsgType("image");
            // 回复文本消息   
            TextMessage textMessage = new TextMessage();  
            textMessage.setToUserName(fromUserName);  
            textMessage.setFromUserName(toUserName);  
            textMessage.setCreateTime(new Date().getTime());
            textMessage.setMsgType("text");  
            
            //回复图文消息
            NewsMessage newsMessage = new NewsMessage();  
            newsMessage.setToUserName(fromUserName);  
            newsMessage.setFromUserName(toUserName);  
            newsMessage.setCreateTime(new Date().getTime());  
            newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
            newsMessage.setFuncFlag(0);  
            
            //设置经纬度
              
            // 文本消息   
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) { 
            	//System.out.println(msgType);
            	//System.out.println("22222222222222");
            	String content = requestMap.get("Content");
            	//System.out.println("content:"+content);
            	IndexDao dao=new IndexDao();
            	Keyword keyword=dao.findkeyword(content);
            	if(keyword==null||keyword.equals("")){
            		respMessage = null;
            		respContent="";
            	}else{
            		respMessage = null;
            		respContent="欢迎关注";
					/*关注回复，图文回复？ 创建图文消息*/
//					List<Article> articleList = new ArrayList<Article>();
//					// 单图文消息
//					// content
//					Article article = new Article();
//					article.setTitle(keyword.getTitle());
//					article.setDescription(keyword.getMiaoshu());
//					article.setPicUrl(keyword.getImg());
//					article
//							.setUrl("http://taoxie.xmyunxin.com/w/keyword!findbyid.action?id1="
//									+ keyword.getId());
//					articleList.add(article);
//					// 设置图文消息个数
//					newsMessage.setArticleCount(articleList.size());
//					// 设置图文消息包含的图文集合
//					newsMessage.setArticles(articleList);
//					// 将图文消息对象转换成xml字符串
//					respMessage = MessageUtil.newsMessageToXml(newsMessage); 
            	}
            
            }  
            // 图片消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {  
            	respContent=""; 
            }  
            // 地理位置消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
            	//经度            	
            	String longitude = requestMap.get("Longitude");
//              //纬度
            	String latitude = requestMap.get("Latitude");
            	respContent=""; 
            }  
            // 链接消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {  
            	respContent=""; 
            }  
            // 音频消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {  
            	respContent=""; 
            }  
            // 事件推送   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) { 
            	//System.out.println("事件推送哈哈哈哈哈哈哈哈哈");
                // 事件类型   
                String eventType = requestMap.get("Event");  
                // 订阅 （关注）  
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                	//System.out.println(" 订阅 （关注）  ");
                	String e = requestMap.get("EventKey"); 
            		if(e==null||e.equals("")||!e.startsWith("qrscene_")){//普通关注
            			  String openid = requestMap.get("FromUserName"); 
                  	  	  Team t=teamDao.findbysellerid(openid);
	                  	  if(t==null){
	                  		 Team team = new Team();
	                  		 team.setOpenid(openid);
	                  		 team.init();
							 teamDao.add(team);
							 //获取头像昵称
							 AccessToken at = WeixinUtil.getAccessToken();
							 String access_token = at.getToken();
							 String url1="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
		        			 JSONObject jsonObject1 = CommonUtil.httpsRequest(url1, "GET", null);
		        			 openid = jsonObject1.getString("openid");
		        			 String nickname = jsonObject1.getString("nickname");
		        			 String img = jsonObject1.getString("headimgurl");
		        			 String sex = jsonObject1.getString("sex");
		        			  
		        			 team.setImg(img);
		        			 team.setSex(sex);
		        			 team.setNickname(Delemoji.emojiChange(nickname));
		        			 teamDao.update(team);
	                  	  }
                  	}else{//扫描关注
                  		try{
	                  		System.out.println("扫描关注开始！");
							String openid = requestMap.get("FromUserName");
							Team t = teamDao.findbysellerid(openid);
							if(t == null) {
								Team team = new Team();
		                  		team.setOpenid(openid);
		                  		team.init();
								teamDao.add(team);
								
								AccessToken at = WeixinUtil.getAccessToken();
								 String access_token = at.getToken();
								 String url1="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
			        			 JSONObject jsonObject1 = CommonUtil.httpsRequest(url1, "GET", null);
			        			 openid = jsonObject1.getString("openid");
			        			 String nickname = jsonObject1.getString("nickname");
			        			 String img = jsonObject1.getString("headimgurl");
			        			 String sex = jsonObject1.getString("sex");
			        			  
			        			 team.setImg(img);
			        			 team.setSex(sex);
			        			 team.setNickname(Delemoji.emojiChange(nickname));
			        			 teamDao.update(team);
							}
                  		}catch(Exception e0){
                  			e0.printStackTrace();
                  		}
                 	}
            		/*扫码关注回复，图文回复？*/
					// 创建图文消息
//					List<Article> articleList = new ArrayList<Article>();
//					// 单图文消息
//					Guanzhu guanzhu = new Guanzhu();
//					guanzhu = guanzhuDao.find();
//					Article article = new Article();
//					article.setTitle(guanzhu.getTitle());
//					article.setDescription(guanzhu.getMiaoshu());
//					article.setPicUrl(guanzhu.getImg());
//					article
//							.setUrl("http://taoxie.xmyunxin.com/w/guanzhu!find1.action");
//					articleList.add(article);
//					// 设置图文消息个数
//					newsMessage.setArticleCount(articleList.size());
//					// 设置图文消息包含的图文集合
//					newsMessage.setArticles(articleList);
//					// 将图文消息对象转换成xml字符串
//					respMessage = MessageUtil.newsMessageToXml(newsMessage);
//					respMessage = null;
					respContent = "欢迎关注";
                }  
                // 自定义菜单点击事件   
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  
                	// 事件KEY值，与创建自定义菜单时指定的KEY值对应   
                    String eventKey = requestMap.get("EventKey");  
                    String openid = requestMap.get("FromUserName"); 
                    if(eventKey.equals("qiandao")){
                    	//对应的click事件做出对应的处理
                    }
                    
                }
            } else {
            	respContent="";
            }
            if(respMessage==null){
            	textMessage.setContent(respContent);  
            	respMessage = MessageUtil.textMessageToXml(textMessage);  
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        return respMessage;
    }  
    
	public static String loadJSON (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                        yc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
		}
        return json.toString();
    }
	
	public static void main(String[] args) {
//		 JSONObject jSONObject = UploadVoice.addSucai("image", t.getHaibao());
//		   //JSONObject jSONObject1 = UploadVoice.addMaterialEver("image", waterFilePath);
//		   //下载
//		   //String xiazai = DownloadVoice.downloadMedia(jSONObject.getString("media_id"),path);
//		   Image Image= new Image();
//		   Image.setMediaId(jSONObject.getString("media_id"));
//		   imgMessage.setImage(Image);
//		   respMessage = MessageUtil.imgMessageToXml(imgMessage);
	}
}  


